package com.zpp.common.message.service;

import jakarta.mail.internet.MimeMessage;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import java.util.Optional;

public class MailService {
    private MailProperties mailProperties;
    private JavaMailSender javaMailSender;

    public MailService(JavaMailSender javaMailSender, MailProperties mailProperties) {
        this.javaMailSender = javaMailSender;
        this.mailProperties = mailProperties;
    }

    public void send(String toEmail,  String code) throws Exception {
        //创建一个邮件消息
        MimeMessage message = javaMailSender.createMimeMessage();
        //创建helper
        MimeMessageHelper helper = new MimeMessageHelper(message, false);

        //获取发送人名称
        String personal = Optional.ofNullable(mailProperties.getProperties().
                get("personal")).orElse(mailProperties.getUsername());

        //设置发送人的邮箱和名称
        helper.setFrom(mailProperties.getUsername(), personal);
        //收件人邮箱
        helper.setTo(toEmail);
        //邮件标题
        helper.setSubject("用户登录验证码");

        //邮件正文
        helper.setText(buildEmailHtml(toEmail, code, 5, personal),true);

        //发送
        javaMailSender.send(message);
    }

    public static String buildEmailHtml(String username, String code, int expireMinutes, String appName) {
        String template = "<!doctype html><html lang=\"zh-CN\"><head><meta charset=\"utf-8\" /><title>验证码邮件</title></head>"
                + "<body style=\"margin:0;padding:0;background:#f6f8fa;font-family:'Segoe UI',Arial,'Microsoft YaHei',sans-serif;\">"
                + "<div style=\"width:90%;max-width:1500px;margin:40px auto;background:#ffffff;border-radius:8px;padding:32px;box-shadow:0 2px 8px rgba(0,0,0,0.05);\">"
                + "<h2 style=\"margin:0 0 20px 0;color:#333;font-size:22px;\">" + appName + " 验证码</h2>"
                + "<p style=\"font-size:16px;color:#555;margin:0 0 12px 0;\">您好，" + username + "：</p>"
                + "<p style=\"font-size:15px;color:#555;line-height:1.6;margin:0 0 20px 0;\">您的验证码为：</p>"
                + "<div style=\"text-align:center;background:#007bff;color:#fff;font-size:28px;font-weight:600;letter-spacing:4px;padding:14px 0;border-radius:6px;margin-bottom:24px;\">"
                + code + "</div>"
                + "<p style=\"font-size:14px;color:#888;margin:0 0 10px 0;\">有效期：" + expireMinutes + " 分钟，请勿泄露给他人。</p>"
                + "<p style=\"font-size:12px;color:#aaa;margin:0;\">本邮件由系统自动发送，请勿回复。</p>"
                + "</div></body></html>";
        return template;
    }


}
